<?php
namespace XFCore\traits\api;
use lib\{PayUtils,AesRsa_Encrypter};
trait NotifyTrait {
    protected $row;
    protected $data;
    public function notify($data){
        $pid = $data['pid'];
        if(empty($pid)){
            $this->echomsg('html','fail');
        }
        $userrow = $this->db->userrow($pid , 'pid');
        if(empty($userrow)){
            $this->echomsg('html','fail');
        }
        if($userrow['api_mode'] == 2){
            
            $data = $this->decodersatoken($userrow,$data['token']);
            if(empty($data)){
                $this->echomsg('html','fail');
            }
            
        }
        
        $prestr=PayUtils::createLinkstring(PayUtils::argSort(PayUtils::paraFilter($data)));
        if(!PayUtils::md5Verify($prestr, $data['sign'], $userrow['key'])){
            $this->echomsg('html','fail');
        }
        unset($userrow);
        
        $row = $this->db->select('insideorder','*',['status'=>0,'order'=>$data['out_trade_no']],['single_row'=>true,'limit'])['result'];
        if(empty($row)){
            $this->echomsg('html','success');
        }
        $this->row = $row;
        $this->data = $data;
        $userrow = $this->db->userrow($row['pid'] , 'pid','`money`,`pid`,`user`,`alipay_free_vip_time`,`wxpay_free_vip_time`,`qqpay_free_vip_time`');
       if(empty($userrow)){
           $this->echomsg('html','success');
       }
       
        /////////////////////////////////////////////////////////
        $rowdata = explode('|',$row['beizhu']);
        $value = $rowdata[0];
        
        switch ($value) {
            case 'pay_money':
                $meals = is_array($this->conf->pay_meal) ? $this->conf->pay_meal : [];
                $rechargeAmount = $row['money'];
                // 初始化最终金额
                $finalAmount = $rechargeAmount;
                
                // 查找是否有匹配的套餐
                $foundMeal = false;
                foreach ($meals as $meal) {
                    if ($rechargeAmount == $meal['recharge']) {
                        $finalAmount = $meal['money'];
                        $foundMeal = true;
                        break;
                    }
                }
                
                if (!$foundMeal) {
                    $finalAmount = $rechargeAmount * $this->conf->ed_money;
                }
                $money = round($userrow['money'] + $finalAmount, 2);
                    
                $this->db->update('user',['money'=>$money],['pid'=>$userrow['pid']]);
                $this->db->update('insideorder',['status'=>1],['id'=>$row['id']]);
                createLog('充值额度成功！',http_ip(),$userrow['user']);
                
                break;
            case 'pay_vip':
                $this->user_vip_Renew($userrow,$rowdata[1]);
                break;
            case 'pay_packages':
                $this->user_packages_buy($userrow , $rowdata[1]);
                break;
            case 'pay_cs':
                $this->db->update('insideorder',['status'=>1],['id'=>$row['id']]);
                createLog('支付测试自动回调成功！',http_ip(),$userrow['user']);
                break;
            case 'reg':
                $this->user_reg_buy($rowdata[1]);
                $this->db->update('insideorder',['status'=>1],['id'=>$row['id']]);
                break;
            
        }

        $this->echomsg('html','success');
    }
    protected function user_reg_buy($token){
        $params = json_decode(aes256auth($token , SYS_KEY , "DECODE"),true);
        if(empty($params)){
            return false;
        }
        if($this->db->insert('user',$params)){
            $sub = $this->conf['sitename'] . ' - 商户注册成功提醒';
            $msg = $this->MsgNotice->send('reg',$this->conf->sitename . '用户',$params);
            send_mail($params['email'], $sub, $msg);
            return true;
        }
    }
    protected function user_packages_buy($userrow , $id){
        $row = $this->db->packagerow($id);
        if($row['status'] == 0 || empty($row)){
            return false;
        }
        
        if($this->data['money'] == $row['price']){
            $params = [];
            
            if(!empty($row['days']) && $row['days'] >0  && is_numeric($row['quota'])){
                $typedata = ['alipay','qqpay','wxpay'];
                foreach ($typedata as $type){
                    $vip = $type.'_free_vip_time';
                    $vipTime = strtotime($userrow[$vip]);
                    $currentDate = strtotime($this->date);
                    if ($vipTime < $currentDate) {
                        $newVipTime = strtotime("+{$row['days']} days", $currentDate);
                    } else {
                        // 如果会员时间未过期，从会员时间开始叠加
                        $newVipTime = strtotime("+{$row['days']} days", $vipTime);
                    }
                    $newVipTimeStr = date("Y-m-d H:i:s", $newVipTime);
                    $params[$vip] = $newVipTimeStr;
                }
            }
            if(!empty($row['quota']) && $row['quota'] > 0 && is_numeric($row['quota'])){
                $params['money'] = round($userrow['money'] + $row['quota'], 2);
            }
            if(!empty($params)){
                $this->db->update('user',$params,['pid'=>$userrow['pid']]);
            }
            $this->db->update('insideorder',['status'=>1],['id'=>$this->row['id']]);
            createLog('购买套餐下发成功！',http_ip(),$userrow['user']);
            return true;
        }
        return false;
    }
    protected function user_vip_Renew($userrow, $type){
        $money = $this->conf[$type . '_free_vip_money'];
        
        if($this->data['money'] == $money){
            
            $vip = $type.'_free_vip_time';
            $vipTime = strtotime($userrow[$vip]);
            $currentDate = strtotime($this->date);
            if ($vipTime < $currentDate){
                $newVipTime = strtotime("+1 month", $currentDate);
            }else{
                $newVipTime = strtotime("+1 month", $vipTime);
            }
            $newVipTimeStr = date("Y-m-d H:i:s", $newVipTime);
            $params = [
                $vip =>$newVipTimeStr
            ];
            
            $this->db->update('user',$params,['pid'=>$userrow['pid']]);
            $this->db->update('insideorder',['status'=>1],['id'=>$this->row['id']]);
            createLog('开通/续费会员成功！',http_ip(),$userrow['user']);
        }
        
        return false;
    }
    
    
}

?>